package cn.itmtr.document.download.common.validator;

import cn.itmtr.document.download.common.exception.ItmtrException;
import cn.itmtr.document.download.common.exception.ItmtrExceptionEnum;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * hibernate-validator校验工具类
 * <p>
 * 参考文档：http://docs.jboss.org/hibernate/validator/5.4/reference/en-US/html_single/
 *
 * @author mtr
 * @since 2021-08-08
 */
public class ValidatorUtil {

    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     * @author mtr
     * @date 2021/8/8
     */
    public static void validateObj(Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            for (ConstraintViolation<Object> constraint : constraintViolations) {
                throw new ItmtrException(ItmtrExceptionEnum.ERROR_PARAM.getCode(), constraint.getMessage());
            }
        }
    }

}
